package alpha.com.google.code.mechanic.janitor.ui;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;

import alpha.com.google.code.mechanic.janitor.controller.TaskTypeConventer;

import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.EpfFileModel;
import com.google.eclipse.mechanic.internal.EpfFileModelWriter;
import com.google.eclipse.mechanic.internal.TaskType;

/**
 * 
 * The class is to help users save the new preferences to an existing/a new Task.
 * 
 * Last_edited: Oct 7, 2014
 *
 * @author jingjiejiang
 * @since Oct 5, 2014
 */
public class PrefRecorderOutputWizard extends Wizard {

  private SavedPrefsWizardPage pageSavedPrefs;
  private ExistingTasksWizardPage pageExistTasks;
  private NewTaskWizardPage pageNewTask;
  
  // The attribute is to indicate whether save the new preferences to
  // a new Task
  private boolean isSaveToNewTask = true;
  
  public PrefRecorderOutputWizard(Map<String, String> preferences) {
    setWindowTitle("New Wizard");
    
    pageSavedPrefs = new SavedPrefsWizardPage(isSaveToNewTask, preferences);
    pageExistTasks = new ExistingTasksWizardPage();
    pageNewTask = new NewTaskWizardPage();
  }

  public boolean isSaveToNewTask() {
    return isSaveToNewTask;
  }

  public void setSaveToNewTask(boolean isSaveToNewTask) {
    this.isSaveToNewTask = isSaveToNewTask;
  }

  @Override
  public void addPages() {
    addPage(pageSavedPrefs);
    addPage(pageExistTasks);
    addPage(pageNewTask);
  }

  @Override
  public boolean performFinish() {
    
    if (true == pageSavedPrefs.isSaveToNewTask()) {
      
      boolean success = true;
      try {
        savePrefsToNewTask();
      } catch (IOException error) {
        MessageDialog.openError(getShell(), "Couldn't have the new preferences"
            , error.getMessage());
        success = false;
      }
      if (success) {
        MessageDialog.openInformation(getShell(), "Information", "The prefereaces has"
            + " been saved successfully.");
      }
    }
    else {
      if (insertPrefsToSelTask()){
        MessageDialog.openInformation(getShell(), "Information", "The prefereaces has"
            + " been successfully inserted into the specified Task.");
      }
    }
    
    return true;
  }
  
  private boolean insertPrefsToSelTask() {
    
    Object[] selTask = pageExistTasks.getSelTask();
    
    // Only allow to insert into one Task at the moment.
    for (Object object : selTask) {
      
      Task task = (Task) object;
      TaskType type = TaskTypeConventer.getTaskTypeFromId(task.getId());
      EpfFileModel epfFile = new EpfFileModel(task.getTitle(),
          task.getDescription(), type);
      
      Map<String, String> selprefs = pageSavedPrefs.getSelectedPrefs();
      Map<String, String> oldprefs = task.getKeyPairs();
      // Add the new preferences to the key/value pairs of the specified task.
      oldprefs.putAll(selprefs);
      
      for (Map.Entry<String, String> entry : oldprefs.entrySet()) {
        epfFile.addElement(entry.getKey(), entry.getValue());
      }
        
      String location = getSelTaskDir(task);
      if (location.equals("")) {
        return false;
      }
      
      IPath path = new Path(location);
      try {
        EpfFileModelWriter.write(epfFile, path);
      } catch (IOException e) {
        MessageDialog.openError(getShell(), "Unable to insert new preferences"
            + " to the specified Task", e.getMessage());
        return false;
      }
    }
    
    return true;
  }
  
  private String getSelTaskDir (Task task) {
    
    String[] idinfo = task.getId().split("@");
    
    return idinfo[1];
  }
  
  private boolean savePrefsToNewTask() throws IOException {
    
    String dir = pageNewTask.getCtxFileLocation() + File.separator
        + pageNewTask.getTxtTaskFileId() + ".epf";
    IPath path = new Path(dir);
    
    EpfFileModel epfFile = new EpfFileModel(pageNewTask.getTaskTitle(),
        pageNewTask.getDescription(), pageNewTask.getTaskType());
    Map<String, String> selprefs = pageSavedPrefs.getSelectedPrefs();
    
    for (Map.Entry<String, String> entry : selprefs.entrySet()) {
      epfFile.addElement(entry.getKey(), entry.getValue());
    }
    
    try {
      EpfFileModelWriter.write(epfFile, path);
    } catch (IOException e) {
      throw new IOException ("Unable to write Preferences file to " + path
          + ": " + e.getMessage());
    }
    
    return true;
  }
  
  @Override
  public IWizardPage getNextPage (IWizardPage page) {
    
    if (true == pageSavedPrefs.isSaveToNewTask()) {
      return pageNewTask;
    }
    else {
      return pageExistTasks;       
    }
  }
  
  @Override
  public boolean canFinish () {
    
    if (true == pageSavedPrefs.isSaveToNewTask()) {
      
      if (false == pageNewTask.getTaskTitle().equals("")
          && false == pageNewTask.getTaskDesc().equals("")
          && false == pageNewTask.getTxtTaskFileId().equals("")) {
        if (false == pageNewTask.getCurCtxName().equals("")
            || false == pageNewTask.getNewCtxName().equals("")) {
          return true;
        }
        else {
          return false;
        }
      }
      else {
        return false;
      }
    }
    else {
      
      // If none of listed Task is selected, return false;
      // otherwise, return true.
      if (pageExistTasks.hasCheckedTask()) {
        return true;
      }
      else {
        return false;
      }
    }
    
  }
  
}
